<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;
use think\Exception;
use think\Cache;
/**
 * 首页接口
 */
class Order extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /**
     * 订单提交接口
     * @ApiMethod (POST)
     * @ApiRoute ("/api/order/submit")
     */
    public function submit()
    {
        // 接收请求参数
        $orders = request()->param('orderData/a', []);
        $requestId = request()->param('request_id', '');

// dump($orders);
        try {
            // 参数基础校验
            if (empty($orders) || !is_array($orders)) {
                throw new Exception('订单数据格式错误');
            }
            if (empty($requestId)) {
                throw new Exception('请求唯一标识不能为空');
            }
            // 检查缓存锁
            if (Cache::has('order_request_' . $requestId)) {
                throw new Exception('重复请求，请勿重复提交');
            }
            
           // 设置缓存锁，有效期1分钟
           Cache::set('order_request_' . $requestId, 1, 60);
            Db::startTrans(); // 开启事务

           // 批量生成订单
           $orderList = [];
           $taocanList = [];
            // 生成订单号
            $orderNo = $this->generateOrderNo();
            foreach ($orders as $key => $item) {
                // 参数校验
                if (empty($item['goods_id'])) {
                    throw new Exception("第" . ($key + 1) . "个订单缺少商品ID");
                }

                // 关联套餐校验（如果存在taocan_id）
                if (!empty($item['taocan_id'])) {
                    $taocanExists = Db::name('jeek_products_price')
                        ->where('id', $item['id'])
                        ->find();
                    if (!$taocanExists) {
                        throw new Exception("第" . ($key + 1) . "个订单的套餐不存在");
                    }
                }


                // 组装订单数据
                $orderList[] = [
                    'user_id'     => $item['user_id'] ?? 0,
                    'goods_id'    => $item['goods_id'],
                    'taocan_id'   => $item['taocan_id'] ?? null,
                    'price'       => $item['price'] ?? 0.00,
                    'quantity'    => $item['quantity'] ?? 1,
                    'image'       => $item['image'] ?? '',
                    'title'       => $item['title'] ?? '',
                    'status'      => 1, // 1-已下单
                    'order_no'    => $orderNo,
                    'createtime' => time(),
                    'updatetime' => time()
                ];

                    // 处理关联的套餐数据
                    if (!empty($item['taocan'])) {
                        if (!is_array($item['taocan'])) {
                            throw new Exception("第" . ($key + 1) . "个订单的套餐数据格式错误");
                        }

                        foreach ($item['taocan'] as $taocanKey => $taocanItem) {
                            if (empty($taocanItem['id'])) {
                                throw new Exception("第" . ($key + 1) . "个订单的第" . ($taocanKey + 1) . "个套餐缺少套餐ID");
                            }

                            // 校验套餐是否存在
                            $taocanExists = Db::name('jeek_products_price')
                                ->where('id', $taocanItem['id'])
                                ->find();
                            if (!$taocanExists) {
                                throw new Exception("第" . ($key + 1) . "个订单的第" . ($taocanKey + 1) . "个套餐不存在");
                            }

                            // 组装套餐数据
                            $taocanList[] = [
                                'order_nos'    => null, // 后续填充订单ID
                                'product_id'   => $taocanItem['product_id'],
                                'title'       => $taocanItem['title'] ?? '',
                                'price'       => $taocanItem['price'] ?? 0.00,
                                'quantity'    => $taocanItem['quantity'] ?? 1,
                                'createtime'  => time(),
                                'updatetime'  => time()
                            ];
                        }
                    }
            }

            // 批量插入订单
            $orderModel = new \app\common\model\jeek\Order();
            $result = $orderModel->saveAll($orderList);
             // 将结果转换为集合对象
             $resultCollection = collection($result);

// dump($result);die();
            // 获取生成的订单ID集合
            $orderIds = array_column($resultCollection->toArray(), 'id');
            // 填充订单ID到套餐数据
            foreach ($result as $index => $order) {
                if (!empty($taocanList)) {
                    foreach ($taocanList as &$taocan) {
                        if ($taocan['order_nos'] === null) {
                            $taocan['order_nos'] = $order->order_no;
                        }
                    }
                }
            }
            // 批量插入套餐数据
            if (!empty($taocanList)) {
                $taocanModel = new \app\common\model\jeek\order\Taocan();
                $taocanModel->saveAll($taocanList);
            }

            Db::commit(); // 提交事务

            return json([
                'code' => 1,
                'msg'  => '批量订单创建成功',
                'data' => [
                    'orderNo' => $orderNo,
                    'count'     => count($orderIds)
                ]
            ]);

        } catch (Exception $e) {
            Db::rollback(); // 回滚事务
                        // 删除缓存锁
                        Cache::delete('order_request_' . $requestId);
            return json([
                'code' => 0,
                'msg'  => $e->getMessage(),
                'data' => []
            ]);
        }
    }

    /**
     * 获取订单详情
     * @ApiMethod (GET)
     * @ApiRoute ("/api/order/detail")
     */
    public function getOrderDetail()
    {
        // 接收请求参数
        $orderNo = request()->param('order_no', '');

        try {
            // 参数基础校验
            if (empty($orderNo)) {
                throw new Exception('订单号不能为空');
            }

            // 查询订单信息
            $order = Db::name('jeek_order')
                ->where('order_no', $orderNo)
                ->select();
            if (!$order) {
                throw new Exception('订单不存在');
            }

            foreach ($order as $key => $value) {
                
                    $taocan = Db::name('jeek_order_taocan')
                    ->where('product_id', $value['goods_id'])
                    ->where('order_nos', $value['order_no'])
                        ->select();
                    $order[$key]['taocan'] = $taocan;
                
            }
          
            // 组装订单详情
            $orderDetail = [
                'orderData' => $order,
            ];

            return json([
                'code' => 1,
                'msg'  => '订单详情获取成功',
                'data' => $orderDetail
            ]);

        } catch (Exception $e) {
            return json([
                'code' => 0,
                'msg'  => $e->getMessage(),
                'data' => []
            ]);
        }
    }

    /**
     * 生成订单号
     * @return string
     */
    private function generateOrderNo()
    {
        // 获取当前时间戳
        $timestamp = time();

        // 生成一个6位随机数
        $random = sprintf('%06d', mt_rand(0, 999999));

        // 组合订单号
        $orderNo = date('YmdHis', $timestamp) . $random;

        return $orderNo;
    }
}